import {
	businessReceiving
} from '@/api/common.js'
import {
	getPhone
} from '@/api/login/login.js';
import store from '@/store/index.js'

const goPages = (url) => {
	uni.navigateTo({
		url: url
	})
}
const goTab = (url) => {
	uni.switchTab({
		url: url
	})
}

const hideKey = () => {
	uni.hideKeyboard();
}
const oversize = () => {
	uni.showToast({
		title: '图片最大不能超过600KB',
		icon: 'none'
	});
}

// 提示未登录-跳转登录页面
const toLogin = () => {
	uni.showModal({
		title: "提示",
		content: "还未登录，马上去登录",
		showCancel: true,
		cancelText: '取消',
		confirmText: '去登录',
		success: res => {
			if (res.confirm) {
				uni.navigateTo({
					url: '/subPages/login/wx_login'
					// url: '/pages/login/wx_login'
				})
			} else {
				// 否则点击了取消  
				return
			}
		}
	})
}

// 消息提醒
const messageTips = () => {
	businessReceiving({
		token: uni.getStorageSync('userInfo').token || ''
	}).then(res => {
		if (res.status === 1) {
			uni.showTabBarRedDot({ //显示红点
				index: 2 //tabbar下标
			})
			getApp().globalData.dot = true
		} else {
			uni.hideTabBarRedDot({ //隐藏红点
				index: 2
			})
			getApp().globalData.dot = false
		}
	})
}

// 快速登录
const getLogin = (phoneCode) => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			onlyAuthorize: true,
			success: async res => {
				if (res.errMsg == 'login:ok') {
					return getphone(phoneCode).then(res => {
						resolve();
					}).catch(err => {
						resolve(err);
					})
				} else {
					uni.$u.toast('微信授权失败，请重试')
					resolve();
				}
			}
		});
	})
}
const getphone = (phoneCode) => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			onlyAuthorize: true,
			success: async logRes => {
				getPhone({
					code: phoneCode,
					log_code: logRes.code
				}).then(res => {
					if (res.code == 0) {
						let msg = {
							logType: 3,
							username: res.data.phone, //手机号
							openid: res.data.openid,
							code: logRes.code //微信code
						}
						store.dispatch('login/Login', msg).then(() => {
							resolve();
						}).catch(err => {
							resolve(err)
						})
					} else {
						uni.$u.taost(res.msg)
						resolve(res.msg);
					}
				});
			}
		});
	})
}

export {
	goPages,
	goTab,
	hideKey,
	toLogin,
	oversize,
	messageTips,
	getLogin
}